package com.kfgj.hkp.common.user.business.impl;

import com.kfgj.hkp.common.user.business.IBaseUserManager;
import com.kfgj.hkp.common.user.dao.IBaseUserDbDao;
import com.kfgj.hkp.common.user.dao.IBaseUserRedisDao;
import com.kfgj.hkp.common.user.entity.BaseUserEntity;
import com.kfgj.hkp.manager.AbstractManager;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created by liwensihan on 2018/5/18.
 */
public abstract class AbstractBaseUserManager<T extends BaseUserEntity> extends AbstractManager<T> implements IBaseUserManager<T> {

    @Autowired
    protected IBaseUserDbDao<T> loginUserDbDao;
    @Autowired
    protected IBaseUserRedisDao<T> loginUserRedisDao;

    /**
     * 可以在项目中进行扩展变更
     * @return
     */
    protected String getUserCodeFieldName(){

        return "userCode";
    }

    @Override
    public T findUserByAuthKey(String authKey) {

        String userCode = loginUserRedisDao.getLoginUserCode(authKey);

        if (StringUtils.isEmpty(userCode)){
            return null;
        }

        T user = loginUserRedisDao.getUserInfo(userCode);

        if(user == null){
            user = findUserByUserCode(userCode);

            if(user != null){
                loginUserRedisDao.setUserInfo(user.getUserCode(),user);
            }else{
                loginUserRedisDao.deleteAuthKey(authKey);
                return null;
            }
        }

        return user;
    }

    @Override
    public T findUserByUserCode(String userCode) {
        return loginUserDbDao.selectUniqueByProp(getUserCodeFieldName(),userCode);
    }

    @Override
    public long getTokenExpire() {
        return 0;
    }

    @Override
    public void saveAuthKey(String authKey, String userCode) {
        loginUserRedisDao.setLoginUserCode(authKey,userCode);
    }

    @Override
    public void updateAuthKeyExpire(String authKey,long expire) {

        loginUserRedisDao.updateAuthKeyExpire(authKey,expire);
    }

    @Override
    public void deleteUserLoginAuthKey(String authKey) {

        loginUserRedisDao.deleteAuthKey(authKey);
    }

}
